package test.transferFile.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import test.transferFile.codec.TransferFileCodecFactory;

public class MinaFileServer {

  private NioSocketAcceptor acceptor;

  public void startServer() {
    acceptor=new NioSocketAcceptor();
    DefaultIoFilterChainBuilder chain=acceptor.getFilterChain();
    chain.addLast("transferFileFilter", new ProtocolCodecFilter(new TransferFileCodecFactory(Charset.forName("utf-8"))));
    /**
     * 在加入threadPool时，文件传输出现混乱
     */
    // Executor threadPool=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
    // chain.addLast("threadPool", new ExecutorFilter(threadPool));// 业务逻辑和IO处理逻辑线程分开
    acceptor.setHandler(new MinaFileServerHandler());
    acceptor.getSessionConfig().setReadBufferSize(1024 * 1024);// 1K
    acceptor.getSessionConfig().setSendBufferSize(1024 * 1024);// 1K
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);// 10s空闲
    try {
      acceptor.bind(new InetSocketAddress(9999));
      System.out.println("MinaFileServer started");
    } catch(IOException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    new MinaFileServer().startServer();
  }
}
/***
 * 文件传输协议格式: String fileName; int bodyLength; byte body;
 * 
 * 
 * */
